import {
	mapState,
	mapMutations
} from "vuex"

import {
	// 类别列表
	getCategoryList,
	// 根据类别id查出类别
	productDataListByCategoryId,
	addShoppingCart,
	getProductByName
} from "./api.js"
export default {
	onShow() {
		getCategoryList()
			.then((res) => {
				this.categories = res.data;
				const initialCategoryIndex = this.currentCategory || 0;
				this.productListByCategoryId(res.data[initialCategoryIndex]);
			})
			.catch((error) => {});
	},

	onLoad(options) {

	},

	data() {
		return {
			currentCategory: 0,
			searchName: '',
			categories: [],
			goodsList: []
		}
	},

	methods: {
		//   vuex储存信息
		...mapMutations([
			"setCartCount",
			"setShopInfo", //设置店铺信息
			"setShopPhone", //设置电话
			"setShopStatus", //设置店铺状态
			"initdishListMut", //设置购物车订单
			"setStoreInfo",
			"setBaseUserInfo", //设置用户基本信息
			"setLodding",
			"setToken", //设置token
			"setDeliveryFee", //设置配送费
		]),
		// 从vuex信息
		...mapState([
			"cartCount",
			"shopInfo", //店铺信息
			"shopPhone", //电话
			"orderListData",
			"baseUserInfo", //用户信息
			"lodding",
			"token", //token
			"deliveryFee", //配送费
		]),
		searchProductByName(){
			if(this.searchName.length == 0 ) return
			const params = {
				name: this.searchName
			}
			getProductByName(params).then((res) =>{
				this.currentCategory = res.data[0].category.id;
				this.goodsList = res.data;
			}).catch((err) =>{})
		},
		getProductDetail(item){
			console.log('getProductDetail', item);
			uni.navigateTo({
				url: "/pages/product/productDetail/index?productId="+item.id,
			})
		},
		switchCategory(index) {
			this.currentCategory = index;
			this.productListByCategoryId(this.categories[index]);
		},
		// 添加购物车
		addProductToCart(item) {
			addShoppingCart(item).then((res) => {
				if (res && res.code === 200) {
					uni.showToast({
						title: res.msg,
						icon: "success",
						duration: 1000,
					});
					this.setCartCount( this.cartCount() + 1) 
				} else {
					uni.showToast({
						title: res.msg,
						icon: "fail",
						duration: 1000,
					});
				}
			}).catch((err) => {})
		},
		async productListByCategoryId(params, index) {
			const param = {
				categoryId: params.id,
			}
			await productDataListByCategoryId(param).then((res) => {
				if (res && res.code === 200) {
					this.goodsList = res.data;
				}
			}).catch((err) => {})
			this.currentCategory = index
		},
	}
}